import {Component, OnInit, Renderer2, ViewChild} from '@angular/core';
import {PermissionService} from '../../../service/permission.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {AisiPriceService} from '../aisi-price.service';
import {$e} from 'codelyzer/angular/styles/chars';

@Component({
  selector: 'app-data-config',
  templateUrl: './data-config.component.html',
  styleUrls: ['./data-config.component.scss']
})
export class DataConfigComponent implements OnInit {
  query = {
    page: 1,
    pageSize: 20,
  };
  listOfData = {
    total: 0,
    records: []
  };
  tableData: any[] = [];
  addBrandModal = {
    visible: false,
    loading: false,
    id: '',
    name: '',
    sort: '',
    img: '',
    status: 1
  };
  addSeriesModal = {
    visible: false,
    loading: false,
    id: '',
    name: '',
    brand: '',
    sort: '',
    status: 1
  };
  addTypeModal = {
    visible: false,
    loading: false,
    id: '',
    name: '',
    series: -1,
    brandName: '',
    specifications: [{name: ''}],
    sort: '',
    status: 1
  };
  brandOptions: any[] = []; // 品牌下拉列表
  seriesOptions: any[] = []; // 系列下拉列表
  imageList: any[] = []; // 图片
  previewImg = ''; // 图片预览
  imgIsModify = false;
  mapOfExpandedData: { [key: string]: any[] } = {};
  @ViewChild('specifications', {static: false}) specificationsEl: any;
  // 文件类型校验
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    this.getBase64(file, img => {
      this.previewImg = img;
    });
    this.imgIsModify = true;
    this.imageList = [file];
    return false;
  };

  constructor(
    private nzMessageService: NzMessageService,
    public permission: PermissionService,
    private renderer2: Renderer2,
    private priceService: AisiPriceService,
  ) {
  }

  ngOnInit(): void {
    this.initPage();
  }

  initPage() {
    this.getBrandAndSeries();
    this.queryTableList();
  }

  getBrandAndSeries() {
    this.priceService.httpGet(this.priceService.serviceUrl.brandAndSeries, {}).then((res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.bannerNameList;
        this.seriesOptions = res.data.seriesNameList;
      }
    });
  }

  collapse(array: any[], data: any, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach((d: any) => {
          const target = array.find(a => a.key === d.key)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: any): any[] {
    const stack: any[] = [];
    const array: any[] = [];
    const hashMap = {};
    stack.push({...root, level: 0, expand: false});
    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({...node.children[i], level: node.level! + 1, expand: false, parent: node});
        }
      }
    }

    return array;
  }

  visitNode(node: any, hashMap: { [key: string]: boolean }, array: any[]): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

  // 添加属性 key
  renameIdToKey(list: any) {
    list.forEach((item: any) => {
      item.key = item.id;
      item.children = item.list;
      if (item.children?.length) {
        this.renameIdToKey(item.children);
      } else {
        delete item.children;
      }
    });
  }

  // 查询列表
  queryTableList() {
    this.priceService.httpGet(this.priceService.serviceUrl.dataConfig, {
      page: this.query.page,
      pageSize: this.query.pageSize,
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
        this.tableData = res.data.records;
        this.renameIdToKey(this.tableData);
        this.tableData.forEach((item: any) => {
          this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
        });
      }
    });
  }

  // file转base64
  private getBase64(img: any, callback: (img: string) => void): void {
    const reader = new FileReader();
    // @ts-ignore
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  // 页码改变
  onPageIndexChange(index: number) {
    this.query.page = index;
  }

  // 分页大小改变
  onPageSizeChange(size: number) {
    this.query.page = 1;
    this.query.pageSize = size;
  }

  // 显示品牌模态框
  addBrandModalShow(data?: any) {
    if (data) {
      this.addBrandModal = {
        visible: true,
        loading: false,
        id: data.id,
        name: data.name,
        sort: data.sort,
        img: data.url,
        status: data.status
      };
      this.imageList = []; // 图片
      this.previewImg = data.url; // 图片预览
      this.imgIsModify = false;
    }
    this.addBrandModal.visible = true;
  }

  // 隐藏品牌模态框
  addBrandModalHide() {
    this.addBrandModal = {
      visible: false,
      loading: false,
      id: '',
      name: '',
      sort: '',
      img: '',
      status: 1
    };
    this.imageList = []; // 图片
    this.previewImg = ''; // 图片预览
    this.imgIsModify = false;
  }

  // 保存品牌
  async addBrandModalSave() {
    if (!this.addBrandModal.name) {
      this.nzMessageService.warning('请输入品牌名称');
      return;
    }
    if (this.imgIsModify) {
      this.addBrandModal.loading = true;
      this.addBrandModal.img = await this.priceService.fileUpload(this.imageList[0]) as string;
      this.addBrandModal.loading = false;
    }
    if (!this.addBrandModal.img) {
      this.nzMessageService.warning('请选择图标');
      return;
    }
    if (!(this.addBrandModal.sort + '')) {
      this.nzMessageService.warning('请输入排序');
      return;
    }
    this.addBrandModal.loading = true;
    this.priceService.httpPost(this.priceService.serviceUrl.addAndEditCategory, {
      name: this.addBrandModal.name, // 名
      id: this.addBrandModal.id, // 主键id，更新时需要
      type: 0, // 0-品牌 1-系列名称 2-机型名称
      url: this.addBrandModal.img, // 图片
      sort: this.addBrandModal.sort, // 排序
      status: this.addBrandModal.status, // 0-禁用 1-启用 2-删除
      pId: '', // 新增系列、机型时对应的品牌、系列主键id
      spec: '', // 规格，逗号隔开  示例：64,128
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.initPage();
        this.addBrandModalHide();
      } else {
        this.addBrandModal.loading = false;
      }
    }).finally(() => {
      this.addBrandModal.loading = false;
    });
  }

  // 显示系列模态框
  addSeriesModalShow(data?: any) {
    if (data) {
      this.addSeriesModal = {
        visible: true,
        loading: false,
        id: data.id,
        name: data.name,
        brand: data.pId,
        sort: data.sort,
        status: data.status
      };
    }
    this.addSeriesModal.visible = true;
  }

  // 隐藏系列模态框
  addSeriesModalHide() {
    this.addSeriesModal = {
      visible: false,
      loading: false,
      id: '',
      name: '',
      brand: '',
      sort: '',
      status: 1
    };
  }

  // 保存系列
  addSeriesModalSave() {
    if (!this.addSeriesModal.name) {
      this.nzMessageService.warning('请输入系列名称');
      return;
    }
    if (!this.addSeriesModal.brand) {
      this.nzMessageService.warning('请选择所属品牌');
      return;
    }
    if (!(this.addSeriesModal.sort + '')) {
      this.nzMessageService.warning('请输入排序');
      return;
    }
    this.addSeriesModal.loading = true;
    this.priceService.httpPost(this.priceService.serviceUrl.addAndEditCategory, {
      id: this.addSeriesModal.id, // 主键id，更新时需要
      name: this.addSeriesModal.name, // 名
      type: 1, // 0-品牌 1-系列名称 2-机型名称
      url: '', // 图片
      sort: this.addSeriesModal.sort, // 排序
      status: this.addSeriesModal.status, // 0-禁用 1-启用 2-删除
      pId: this.addSeriesModal.brand, // 新增系列、机型时对应的品牌、系列主键id
      spec: '', // 规格，逗号隔开  示例：64,128
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        // this.queryTableList();
        this.initPage();
        this.addSeriesModalHide();
      } else {
        this.addSeriesModal.loading = false;
      }
    }).finally(() => {
      this.addSeriesModal.loading = false;
    });
  }

  // 显示机型模态框
  addTypeModalShow(data?: any) {
    if (data) {
      this.addTypeModal = {
        visible: true,
        loading: false,
        id: data.id,
        name: data.name,
        series: data.pId,
        brandName: '',
        specifications: data.spec.split(',').map((item: any) => ({name: item})),
        sort: data.sort,
        status: data.status
      };
      this.getBrandBySeries(data.pId, this.addTypeModal);
    }
    this.addTypeModal.visible = true;
    // this.addTypeModal.series = 99;
  }

  // 隐藏机型模态框
  addTypeModalHide() {
    this.addTypeModal = {
      visible: false,
      loading: false,
      id: '',
      name: '',
      series: -1,
      brandName: '',
      specifications: [{name: ''}],
      sort: '',
      status: 1
    };
  }

  // 保存机型
  addTypeModalSave() {
    if (!this.addTypeModal.name) {
      this.nzMessageService.warning('请输入机型名称');
      return;
    }
    if (!this.addTypeModal.series) {
      this.nzMessageService.warning('请选择所属系列');
      return;
    }
    if (this.addTypeModal.specifications.length === 1 && !this.addTypeModal.specifications[0].name) {
      this.nzMessageService.warning('请输入规格');
      return;
    }
    if (!(this.addTypeModal.sort + '')) {
      this.nzMessageService.warning('请输入排序');
      return;
    }
    this.addTypeModal.loading = true;
    this.priceService.httpPost(this.priceService.serviceUrl.addAndEditCategory, {
      id: this.addTypeModal.id, // 主键id，更新时需要
      name: this.addTypeModal.name, // 名
      type: 2, // 0-品牌 1-系列名称 2-机型名称
      url: '', // 图片
      sort: this.addTypeModal.sort, // 排序
      status: this.addTypeModal.status, // 0-禁用 1-启用 2-删除
      pId: this.addTypeModal.series, // 新增系列、机型时对应的品牌、系列主键id
      spec: this.addTypeModal.specifications.filter(item => item.name).map(item => item.name).join(','), // 规格，逗号隔开  示例：64,128
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        // this.queryTableList();
        this.initPage();
        this.addTypeModalHide();
      } else {
        this.addTypeModal.loading = false;
      }
    }).finally(() => {
      this.addTypeModal.loading = false;
    });
  }

  removeSpecification(index: number) {
    this.addTypeModal.specifications.splice(index, 1);
  }

  appendSpecification() {
    this.addTypeModal.specifications.push({name: ''});
    setTimeout(() => {
      this.specificationsEl.nativeElement.scrollTop = this.specificationsEl.nativeElement.scrollHeight > 200
        ? this.specificationsEl.nativeElement.scrollHeight - this.specificationsEl.nativeElement.clientHeight : 0;
      this.renderer2.selectRootElement(`#addTypeModalSpecification${this.addTypeModal.specifications.length - 1}`).focus();
    });
  }

  editRow(item: any) {
    if (item.type === 0) {
      this.addBrandModalShow(item);
    } else if (item.type === 1) {
      this.addSeriesModalShow(item);
    } else if (item.type === 2) {
      this.addTypeModalShow(item);
    }
  }

  seriesChange($event: any) {
    this.addTypeModal.brandName = '';
    if ($event) {
      this.getBrandBySeries($event, this.addTypeModal);
    }
  }

  getBrandBySeries(seriesId: any, obj: any) {
    this.priceService.httpGet(this.priceService.serviceUrl.getBrandBySeries, {seriesId}).then((res: any) => {
      if (res.code === 0) {
        obj.brandName = res.data;
      }
    });
  }

  deleteRow(item: any) {
    this.priceService.httpPost(this.priceService.serviceUrl.addAndEditCategory, {
      id: item.id, // 主键id，更新时需要
      status: 2, // 0-禁用 1-启用 2-删除
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('删除成功');
        this.initPage();
      }
    });
  }
}
